<?php
/**
 * Created by PhpStorm.
 * User: lingyun
 * Date: 2018/1/26
 * Time: 9:08
 * Desc: 会员注册
 */

namespace app\index\controller;
use think\Controller;
use think\Model;
use app\index\controller\Base;
use pinyin\Pinyin;
use controller\BasicWechat;
use app\index\service\WeixinService;

class Register extends Controller{

    public function _initialize(){
        parent::_initialize();
        //微信客户端 -- 获取会员的openid
        if(is_weixin()){    //微信端
            if(empty(session('openid'))) {
                $oauth = new BasicWechat();     //微信授权登录,获取openID
            }
        }
        /**
         * 根据ip定位当前的城市、获取保存的门店或者后台推荐的门店地址
         * 没有推荐门店或者推荐的门店已经关闭选择默认最早添加的店进行推荐
         */
        $cookie_city_key = cookie('city_key');                          //城市key -- 拼音
        $cookie_city_code = cookie('city_code');                        //城市主键表示 -- code
        $cookie_store_id = cookie('store_id');                          //上次选中的门店

        $ip = request()->ip();                                      //获取客户端的IP地址
        $result = get_location_city($ip);                           //返回当前的城市信息
        $pinyin = new Pinyin();                                     //将中文装换成拼音
        $city_key = $pinyin->getAllPY($result['msg']);              //当前城市的key
        $city = db('city')->where('key',$city_key)->find();         //当前的城市信息
        $city_list = db('city')->where(['status'=>1,'is_deleted'=>0])->select();                //切换城市的城市列表
        if(empty($city)){
            $city['value'] = '青岛';
        }
        if($cookie_city_key == '' || $cookie_city_code == '' || $cookie_store_id == ''){            //没有历史记录，重新获取
            $this->assign('is_cookie_city',0);                          //没有选择城市或者门店
//            $this->redirect('Index/index');
        }else{
            cookie('city_key',$cookie_city_key,15552000);               //保存当前的城市代码
            cookie('city_code',$cookie_city_code,15552000);             //城市的代码
            cookie('store_id',$cookie_store_id,15552000);               //城市的代码
            session('store_id',$cookie_store_id);                       //记住门店id
            $this->assign('is_cookie_city',1);                          //已经选择门店或者城市
        }
        $cur_city = db('city')->where('key',cookie('city_key'))->value('value');            //当前的城市名称

        $cart_num = $this->get_cart_amount();           //购物车商品数量

        $this->url = $this->request->url(true);         //登录回调页面
        $this->assign('url',$this->url);
        $this->assign('cur_city',$cur_city);            //当前的城市
        $this->assign('city_list',$city_list);            //当前城市名称
        $this->assign('cur_category',0);                //商品的顶级分类
        $this->assign('city_list',$city_list);               //城市列表
        $this->assign('cart_num',$cart_num);            //购物车数量
        $this->assign('city',$city);            //购物车数量
    }

    /**
     * @Author  lingyun
     * @Desc    购物车数据
     * @return int
     * 2018-04-21
     */
    private function get_cart_amount(){
        $store_id = cookie('store_id');         //当前门店id
        $cart = (array)cookie('user_cart');            //会员购物车
        if(!empty($store_id)){                  //
            foreach($cart as $k => $v){
                if($v['store_id'] != $store_id){
                    unset($cart[$k]);
                }
            }
            $store_goods_stock_id = array_column($cart, 'store_goods_stock_id');
            $goods = db('store_goods_stock')->alias('a')->join('ys_goods b','a.goods_id=b.id')->join('ys_goods_spec_detail c','a.goods_spec_id=c.id','LEFT')->where(['a.is_deleted'=>0,'a.onsale'=>1,'c.is_deleted'=>0,'b.is_deleted'=>0,'status'=>1,'a.id'=>['in',$store_goods_stock_id]])->select();
            return count($goods);
        }else{
            return 0;
        }
    }

    /**
     * @Author  lingyun
     * @Desc    会员注册类
     */
    public function register(){
        $post = input('param.');        //获取信息 -- 主要拿到openID以及分享人的id
        $openid = session('openid');    //微信授权登录的openID

        $sharer = empty($post['sharer'])?'0':$post['sharer'];
        $this->assign('sharer',$sharer);

        return $this->fetch('register');        //注册

        /**
         * 微信端注册判断是否已经注册过
         */
//        if(!empty($openid) && empty(session('_user_uid_.uid'))){
//            $user = db('user')->where('openid',$openid)->find();
//
//            if(!empty($user) && $user['status'] == 0){
//                session('user_forbid',1);       //会员被禁用
//            }
//
//            if(session($user) && $user['is_deleted'] == 1){
//                session('user_forbid',1);       //会员被禁用
//            }
//
//            //信息已完善 -- 跳转到首页
//            if(!empty($user['nickname']) && !empty($user['realname']) && !empty($user['mobile']) && !empty($user['password'])){
//
//                session('_user_uid_.uid',$user['uid']);
//                session('_user_uid_.openid',$user['openid']);
//                session('_user_uid_.nickname',$user['nickname']);
//                session('_user_uid_.realname',$user['realname']);
//                session('_user_uid_.mobile',$user['mobile']);
//
//                $cookie_data = [
//                    'uid'=>$user['uid'],
//                    'mobile'=>$user['mobile'],
//                    'realname'=>$user['realname'],
//                    'nickname'=>$user['nickname'],
//                ];
//                cookie('c_user',$cookie_data,15552000);
//
//                $this->redirect(url("Index/index"));
//            }else{      //没有完善信息 -- 注册完善
//                if(!empty($post['sharer'])){
//                    $this->assign('sharer',$post['sharer']);        //邀请人id
//                }else{
//                    $this->assign('sharer',0);        //邀请人id
//                }
//                return $this->fetch('register');        //去注册
//            }
//        }else{  //非微信端注册
//            $this->assign('sharer',0);
//            return $this->fetch('register');
//        }
    }

    /**
     * @Author  lignyun
     * @Desc    获取短信验证码
     */
    public function get_msg_code(){
        $post = input('post.');
        $time = time();
        $send_msg_time = session('send_msg_time');      //短信的发送时间
        if(!empty($send_msg_time) && ($send_msg_time+60>$time)){
            $this->error('请在1分钟之后重新发送短信验证','');
        }
        $code=rand(100000,999999);
        $response = \SMS::sendSms(config('alidayu.msg_sign'),config('alidayu.msg_template'),$post['mobile'],array("code"=>$code));
        if ($response->Code == 'OK'){
            session('send_msg_time',time());        //记录短信发送时间
            session('send_msg_code',$code);         //记录短信验证码
            session('send_msg_mobile',$post['mobile']);         //记录接受短信的手机
            $this->success('发送成功','');
        }else{
            $this->error('发送失败','');
        }
    }

    /**
     * @Author  lingyun
     * @Desc    提交信息进行注册
     *          只有微信端才可以进行邀请好友注册
     *          会员没有注册过 则进行注册 -- 否则进行修改信息
     *          只要有sharer就是邀请注册 -- 无差别客户端
     *          只给上一级的邀请人进行加分
     *      <pre>array(5) {
            ["nickname"] =&gt; string(9) "刘万君"
            ["mobile"] =&gt; string(11) "18765227746"
            ["verify_code"] =&gt; string(6) "271625"
            ["password"] =&gt; string(6) "123456"
            ["repassword"] =&gt; string(6) "123456"
    }
     */
    public function post_register()
    {
        $post = input('param.');
        if(trim($post['realname']) == ''){
            $this->error('请输入真实姓名','');
        }
        $user = db('user')->where('mobile',$post['mobile'])->find();        //查询会员是否已经注册过了
        if($user['password'] != ''){
            $this->error('该手机号已被占用，请重新输入','');
        }
        //查询会员是否通过其他渠道注册过
        $send_msg_code = session('send_msg_code');      //短信验证码
        $send_msg_time = session('send_msg_time');      //短信发送时间
        $send_msg_mobile = session('send_msg_mobile');  //短信接收的手机
        $reg = "/^[0-9a-zA-Z_]{6,16}$/";

        if(!is_weixin()){               //非微信端注册
            $post['sharer'] = 0;        //将邀请人信息置为0
        }

//        if($send_msg_mobile != $post['mobile']){
//            $this->error('手机号填写错误，请重新填写','');
//        }

        if (!preg_match($reg, $post['password'])) {
            $this->error('密码格式不正确，只能是字母数字下划线6~16位组合', url('Register/register'),3);
        }
        if ($post['password'] != $post['repassword']) {
            $this->error('两次密码输入不一致，请重新填写', url('Register/register'),3);
        }
//        if ($send_msg_code != $post['verify_code']) {
//            $this->error('验证码输入不正确', url('Register/register'),3);
//        }
//        if ($send_msg_time + 7200 < time()) {
//            $this->error('验证码已过期，请重新再试', url('Register/register'),3);
//        }
        $data['password'] = md5($post['password']);
        //注册会员赠送的积分规则
        $rule1 = db('sys_point')->where('code',1)->find();
        $today_time = get_today_time();     //获取今日的起止时间
        $pid = empty($post['sharer'])?0:$post['sharer'];        //邀请人的id -- 上级分享人信息
        $inviter = db('user')->where('uid',$pid)->find();   //邀请人信息
        $rules = db('sys_level')->order('score asc')->select();


        if($pid != 0){      //分享人获取积分
            //查询今日的邀请人数
            $count = db('user')->where(['pid'=>$pid,'addtime'=>['gt',$today_time['start']],'addtime'=>['lt',$today_time['end']]])->count();
            if($count<config('invite_num') && empty($user)){        //会员以前没有注册并且邀请人数不足每日上限
                $rule2 = db('sys_point')->where('code',4)->find();  //邀请会员获得积分
                //赠送邀请人积分
//                $level = userLevel($rules,$inviter['level_point']+$rule2['point']);
                $data_1 = [
//                    'level_point'=>$inviter['level_point']+$rule2['point'],
                    'pay_points'=>$inviter['pay_points']+$rule2['point'],
                    'underling_number'=>$inviter['underling_number']+1,
                    'invite_point'=>$inviter['invite_point']+$rule2['point'],
//                    'level_id'=>$level
                ];
                db('user')->where('uid',$pid)->update($data_1);

                //记录邀请积分记录
                $point2_arr = [
                    'uid'=>$pid,
                    'uidtype'=>3,
                    'signid'=>4,
                    'type'=>1,
                    'point'=>$rule2['point'],
//                    'cur_levelpoint'=>$inviter['level_point']+$rule2['point'],
                    'curpoint'=>$inviter['pay_points']+$rule2['point'],
                    'type_cn'=>'邀请好友注册，获得积分',
                    'remark'=>'邀请好友注册，获得积分',
                    'addtime'=>time(),
                    'tuijianrenuid'=>0
                ];
                db('user_point_log')->data($point2_arr)->insert();

                if(!empty($inviter['pid'])){      //顶级邀请人id
                    $t_invite = db('user')->where('uid',$inviter['pid'])->find();
//                    $level = userLevel($rules,$t_invite['level_point']+floor($rule2['point']/2));
                    $data_2 = [
//                        'level_point'=>$t_invite['level_point']+$rule2['point']/2,
                        'pay_points'=>$t_invite['pay_points']+$rule2['point']/2,
                        'invite_point'=>$t_invite['invite_point']+$rule2['point']/2,
//                        'level_id'=>$level
                    ];
                    db('user')->where('uid',$t_invite['uid'])->update($data_2);
                    $point3_arr = [
                        'uid'=>$t_invite['uid'],
                        'uidtype'=>3,
                        'signid'=>4,
                        'type'=>1,
                        'point'=>floor($rule2['point']/2),
//                        'cur_levelpoint'=>$inviter['level_point']+floor($rule2['point']/2),
                        'curpoint'=>$inviter['pay_points']+floor($rule2['point']/2),
                        'type_cn'=>'下线发展会员，获得积分',
                        'remark'=>'下线发展会员，获得积分',
                        'addtime'=>time(),
                        'tuijianrenuid'=>0
                    ];
                    db('user_point_log')->insert($point3_arr);      //新增会员积分记录
                }

            }else{
                $pid = 0;
            }
        }
        //注册会员信息
        $data_arr = [
            't_pid'=>$inviter['pid'],     //等级分享人的id
            'pid'=>$pid,                    //上级分享人的id
            'openid'=>session('openid'),
            'mobile' => $post['mobile'],
            'realname' => $post['realname'],
            'nickname' => $post['realname'],
            'password' => md5($post['password']),
            'level_id'=>$rules[0]['id'],
//            'level_point'=>$rule1['point'],
            'pay_points'=>$rule1['point'],
            'addtime'=>time()
        ];

        if(empty($user)){       //会员信息为空,注册会员
            $result = db('user')->insertGetId($data_arr);        //注册会员

            if(is_weixin()){        //是否是微信端
                $up_data['openid'] = session('openid');

                $coupon = db('store_coupon')->where(['store_id'=>cookie('store_id'),'type'=>1,'status'=>1,'is_deleted'=>0])->select();
                if(!empty($coupon)){
                    foreach($coupon as $k => $v){       //优惠券列表
                        $coupon_arr[$k] = [
                            'store_id'=>$v['store_id'],
                            'uid'=>$res,
                            'coupon_id'=>$v['id'],
                            'type'=>1,
                            'cat_id'=>$v['cat_id'],
                            'condition'=>$v['condition'],
                            'morethan'=>$v['morethan'],
                            'reduce'=>$v['reduce'],
                            'use_start_time'=>$v['use_start_time'],
                            'use_end_time'=>$v['use_end_time'],
                            'addtime'=>time(),
                            'use_end_time'=>$v['use_end_time'],
                        ];
                    }
                    db('user_ycard')->insertAll($coupon_arr);

                    if(is_weixin()){
                        $root = request()->domain();
                        $send_msg = [
                            "type"   	  =>1,
                            "touser" 	  =>session('openid'),
                            "template_id"=>config("weixin_mu_msg.register_msg")["tempid"],
                            "url" 		  =>$root.'/index.php/index/user/my_coupon',
                            "topcolor"  =>"#743A3A",
                            "data"   =>[
                                "first" 	    =>["value"=>'会员注册成功', "color"=>"#743A3A"],
                                "keyword1"		=>["value"=>$data['mobile'], 		"color"=>"#743A3A"],
                                "keyword2"		=>["value"=>date('Y-m-d H:i',time()), 		"color"=>"#743A3A"],
                                "remark"		=>["value"=>"会员注册成功，已获得优惠券，请到会员中心查看", 			"color"=>"#743A3A"],
                            ]
                        ];
                        $this->sendMessage($send_msg);
                    }
                }
            }

            $up_data['pay_code'] =get_pay_code($result);                       //会员的支付码
            if(is_weixin()){        //是否是微信端
                $up_data['openid'] = session('openid');
            }
            db('user')->where('uid',$result)->update($up_data);        //更新会员支付码、会员openID
//            $level = userLevel($rules,$rule1['point']);
//            db('user')->where('uid',$result)->update(['pay_code'=>$pay_code,'level_id'=>$level]);       //更新会员的支付码

            session('_user_uid_.uid',$result);
            session('_user_uid_.mobile',$data_arr['mobile']);
            session('_user_uid_.realname',$data_arr['realname']);
            session('_user_uid_.nickname',$data_arr['nickname']);

            $cookie_data = [
                'uid'=>$result,
                'mobile'=>$data_arr['mobile'],
                'realname'=>$data_arr['realname'],
                'nickname'=>$data_arr['realname']
            ];
            cookie('c_user',$cookie_data,15552000);          //记住当前登录人的cookie

            //会员注册积分变更记录
            $point1_arr = [
                'uid'=>$result,
                'uidtype'=>3,
                'signid'=>4,
                'type'=>1,
                'point'=>$rule1['point'],
//                'cur_levelpoint'=>$rule1['point'],
                'curpoint'=>$rule1['point'],
                'type_cn'=>'注册会员赠送积分',
                'remark'=>'注册会员赠送积分',
                'addtime'=>time(),
                'tuijianrenuid'=>$pid
            ];
            db('user_point_log')->data($point1_arr)->insert();
        }else{
            db('user')->where('uid',$user['uid'])->update($data_arr);
            //会员注册积分变更记录
            $point1_arr = [
                'uid'=>$user['uid'],
                'uidtype'=>3,
                'signid'=>4,
                'type'=>1,
                'point'=>$rule1['point'],
//                'cur_levelpoint'=>$rule1['point'],
                'curpoint'=>$rule1['point'],
                'type_cn'=>'注册会员赠送积分',
                'remark'=>'注册会员赠送积分',
                'addtime'=>time(),
                'tuijianrenuid'=>$pid
            ];
            db('user_point_log')->data($point1_arr)->insert();
        }

        $this->success('注册会员成功',url('Index/index'),2);
    }

    /**
     * @Author lignyun
     * @Desc    推送模板消息
     */
    private function sendMessage($array){
        $wein = new WeixinService();
        $rest  = $wein->sendmsg($array);
    }




}